package net.maku.events.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import net.maku.events.dao.UserSnapshotDao;
import net.maku.events.entity.UserSnapshotEntity;
import net.maku.framework.mybatis.service.impl.BaseServiceImpl;
import net.maku.events.entity.UserLikesEntity;
import net.maku.events.dao.UserLikesDao;
import net.maku.events.service.UserLikesService;
import net.maku.framework.security.user.SecurityUser;
import org.apache.commons.lang3.ObjectUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
 * 用户点赞记录
 *
 * @author 阿沐 babamu@126.com
 * @since 1.0.0 2025-03-22
 */
@Service
@AllArgsConstructor
public class UserLikesServiceImpl extends BaseServiceImpl<UserLikesDao, UserLikesEntity> implements UserLikesService {

    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean giveOrCancel(Long businessId, Integer businessType) {
        UserLikesEntity userLikesEntity = this.getOne(new LambdaQueryWrapper<UserLikesEntity>()
                .eq(UserLikesEntity::getUserId, SecurityUser.getUser().getId()).eq(UserLikesEntity::getBusinessId, businessId)
                .eq(UserLikesEntity::getBusinessType, businessType));
        boolean addLikeFlag = true;
        if (ObjectUtils.isNotEmpty(userLikesEntity)) {
            this.removeById(userLikesEntity.getId());
            addLikeFlag = false;
        } else {
            userLikesEntity = new UserLikesEntity();
            userLikesEntity.setUserId(SecurityUser.getUser().getId());
            userLikesEntity.setBusinessId(businessId);
            userLikesEntity.setBusinessType(businessType);
            this.save(userLikesEntity);
        }
        return addLikeFlag;
    }

    @Override
    public UserLikesEntity getSelfLike(Long businessId, Integer businessType) {
        return this.getOne(new LambdaQueryWrapper<UserLikesEntity>()
                .eq(UserLikesEntity::getUserId, SecurityUser.getUser().getId()).eq(UserLikesEntity::getBusinessId, businessId)
                .eq(UserLikesEntity::getBusinessType, businessType));
    }

}